package net.starwifi.duobao.web;

import net.starwifi.duobao.SettingUtils;
import net.starwifi.duobao.entity.Wxhd;
import net.starwifi.duobao.mvc.BaseController;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.service.WXCoreService;
import net.starwifi.duobao.service.WXUserService;
import net.starwifi.duobao.service.WxhdService;
import net.starwifi.wx.tools.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 微信活动
 * Created by Administrator on 2015/8/14.
 */
@Controller("apiWxhdController")
@RequestMapping("/wxhd")
public class WXActivityController extends BaseController {


    @Autowired
    WXCoreService wxCoreService;

    @Autowired
    WxhdService wxhdService;

    /**
     * 活动主页
     */
    @RequestMapping(value = "/onehd", method = RequestMethod.GET)
    public String pageOne(ModelMap model, HttpServletRequest request) {


        model.addAttribute("wx_appid", SettingUtils.get("wx_appid"));
        model.addAttribute("token", wxCoreService.getToken());
        String jsapiTicket = wxCoreService.getJsTicket();
        String rand = StringUtils.getUUID();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String siteUrl = SettingUtils.get("siteUrl");
        String url = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
        Map<String, String> map = wxCoreService.getSign(jsapiTicket, siteUrl + url);
        model.addAttribute("timeStamp", map.get("timestamp"));
        model.addAttribute("nonceStr", map.get("nonceStr"));
        model.addAttribute("signaTure", map.get("signature"));
        System.out.print(map);
        return "/wxhd/hd_1";
    }

    @Autowired
    WXUserService wxUserService;

    /**
     * 关注后填写号码领取流量（号码提交）
     */
    @RequestMapping(value = "/onShare", method = RequestMethod.POST)
    @ResponseBody
    public Object onShare(RedirectAttributes redirectAttributes, HttpServletRequest request) {
        Wxhd wxhd = new Wxhd();
        String openId = (String) request.getSession().getAttribute("wx_openid");
        if (openId == null) {
            return Message.error("");
        }
        wxhd = wxhdService.findByOpenId(openId);
        if (wxhd == null) {
            wxhd = new Wxhd();
            wxhd.setOpenid(openId);
            wxhd.setShareDate(new Date());
            wxhd.setShareNum(1);
            wxhdService.save(wxhd);
        } else {
            wxhd.setShareNum(wxhd.getShareNum() + 1);
            wxhdService.update(wxhd);
        }

        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return Message.success("提交成功");
    }

    /**
     * 分享成功后扫码界面
     */
    @RequestMapping(value = "/twohd", method = RequestMethod.GET)
    public String pageTwo(ModelMap model) {
        return "/wxhd/hd_2";
    }


    /**
     * 关注后填写号码领取流量
     */
    @RequestMapping(value = "/threehd", method = RequestMethod.GET)

    public String pageThr(ModelMap model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        model.addAttribute("wx_appid", SettingUtils.get("wx_appid"));
        model.addAttribute("token", wxCoreService.getToken());
        String jsapiTicket = wxCoreService.getJsTicket();
        String rand = StringUtils.getUUID();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String siteUrl = SettingUtils.get("siteUrl");
        String url = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();

        Map<String, String> map = wxCoreService.getSign(jsapiTicket, siteUrl + url);
        model.addAttribute("timeStamp", map.get("timestamp"));
        model.addAttribute("nonceStr", map.get("nonceStr"));
        model.addAttribute("signaTure", map.get("signature"));
        String openId = (String) request.getSession().getAttribute("wx_openid");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {

            Date d1 = df.parse(SettingUtils.get("wx_date"));
            Date d2 = df.parse(df.format(new Date()));
            long diff = d1.getTime() - d2.getTime();

            long days = diff / (1000 * 60 * 60 * 24);
            if(days<=0){
                model.addAttribute("ggloff", "0");
            }else{
                model.addAttribute("ggloff", "1");
            }
            if (openId != null) {
                Wxhd wxhd = wxhdService.findByOpenId(openId);
                if (wxhd != null) {
                    model.addAttribute("u_mobile", wxhd.getMobile());
                } else {
                    model.addAttribute("u_mobile", "");
                }
            }}catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.print(map);
        return "/wxhd/hd_3";
    }


    /**
     * 关注后填写号码领取流量（号码提交）
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Object save(String mobile, RedirectAttributes redirectAttributes, HttpServletRequest request) {
        String openId=(String)request.getSession().getAttribute("wx_openid");

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {

            Date d1 = df.parse(SettingUtils.get("wx_date"));
            Date d2 = df.parse(df.format(new Date()));
            long diff = d1.getTime() - d2.getTime();

            long days = diff / (1000 * 60 * 60 * 24);
            if(days<=0){
                return Message.error("活动已经结束了哦~");
            }
            if(openId==null){
                return Message.error("用户授权失败，请重新授权");
            }
            Wxhd wxhd = wxhdService.findByOpenId(openId);
            if (wxhd == null) {
                wxhd = new Wxhd();
                wxhd.setOpenid(openId);
                wxhd.setShareDate(new Date());
                wxhd.setMobile(mobile);
                wxhd.setShareNum(0);
                wxhdService.save(wxhd);
            } else {
                wxhd.setMobile(mobile);
                wxhdService.update(wxhd);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return Message.success("提交成功");
    }


}
